package com.gitee.wsl.jvm.reflect.autobox

import com.gitee.wsl.jvm.reflect.ReflectionUtils.cast
import java.math.BigDecimal

class BooleanTypeAutoboxer : TypeAutoboxer<Boolean> {
    override fun supports(type: Class<*>): Boolean {
        return Boolean::class.java == type || Boolean::class.javaPrimitiveType == type
    }

    override fun autobox(value: Any, type: Class<Boolean>): Boolean {
        if (value is Boolean) {
            return value
        } else if (value is BigDecimal) {
            return cast(BigDecimal.ZERO != value)
        } else if (value is Int) {
            return cast(value != 0)
        }
        throw UnsupportedOperationException(
            String.format(
                "Cannot autobox %s of type %s to %s",
                value,
                value.javaClass.name,
                Boolean::class.java.name
            )
        )
    }
}
